<template>
  <div>
    <div class="full-screen">
      <div class="form">
        <div class="file-block">
          <h4 class="hairlines">上传附件材料<span> (选填)</span></h4>
          <div class="photo">
            <h5>上传房屋产权证、房屋买卖合同等有效证件能获得<span @click="showMask">更高额度</span></h5>
            <div class="container" v-if="photoImg[0]">
              <img :src="photoImg[0]">
              <input type="file" class="fileInput">
            </div>
            <div class="container" v-if="photoImg[1]">
              <img :src="photoImg[1]">
              <i class="iconfont icon-close" @click="deleteImg(1)"></i>
            </div>
            <div class="container" v-if="photoImg[2]">
              <img :src="photoImg[2]">
              <i class="iconfont icon-close" @click="deleteImg(2)"></i>
            </div>
            <p class="add" v-show="!isMax">继续添加<input type="file" ref="addInput"></p>
          </div>
        </div>
      </div>
      <footer class="form-footer">
        <button class="return hairlines-top" @click="back"><i class="iconfont icon-return2"></i>返回</button>
        <input class="next" type="button" value="保存，下一步" @click="toNext">
      </footer>
    </div>
    <loading-tem v-if="loadingIsShow" :show="loadingIsShow"></loading-tem>
    <tips-tem v-if="maskIsShow" :html="tipsHtml" @hideMask="hideMask" :isNormal="true"></tips-tem>
  </div>
</template>
<script>
  import $ from 'edom'
  import loading from '../loading/loading.vue'
  import tips from '../tips/tips.vue'
  import fileRead from '../../assets/js/fileRead.js'
  import photoImg from '../../assets/img/info-photo.png'

  export default {
    name: 'CheckID',
    components: {
      'loading-tem': loading,
      'tips-tem': tips
    },
    data () {
      return {
        title: '附件资料',
        loadingIsShow: false,
        maskIsShow: false,
        tipsHtml: '添加房产证，车辆行驶证，<br>固定资产证明，工作证等有效证明，<br>可以得到更高额度',
        isMax: false,
        QNYtoken: null,
        photoImg: [photoImg],
        base64Image: [],
        saveData: []
      }
    },
    computed: {
      info () {
        return this.$store.state.profile.attach
      }
    },
    methods: {
      back () {
        this.$router.push('/warrantor/manage')
      },
      toNext () {
        if (this.base64Image.length === 0) {
          $().Mnews('请上传照片', 1000)
          return
        }
        this.loadingIsShow = true
        let QNYPromise = new Promise(this.getQNYToken)
        QNYPromise.then(() => {
          return new Promise(this.uploadQNY)
        }).then(() => {
          this.saveInfo()
        })
      },
      getQNYToken (resolve) {
        this.axios.post('/api/qiniu/get_up_token', {
          user_id: this.$store.state.user_id,
          token: this.$store.state.token
        })
        .then((res) => {
          let data = res.data
          let code = data.code
          let desc = data.desc
          if (code === 200) {
            this.QNYtoken = desc
          } else {
            $().Mnews(desc, 1000)
          }
          resolve()
        })
      },
      uploadQNY (resolve) {
        let length = this.base64Image.length
        let base = 0
        for (let i = 0; i < length; i++) {
          const pic = this.base64Image[i]
          const url = 'http://upload.qiniu.com/putb64/-1'
          const xhr = new XMLHttpRequest()
          xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
              let data = JSON.parse(xhr.responseText)
              this.QNYhash = data.hash
              this.QNYkey = data.key
              this.saveData.push(this.QNYkey)
              base++
              if (base === length) {
                resolve()
              }
            }
          }
          xhr.open('POST', url, true)
          xhr.setRequestHeader('Content-Type', 'application/octet-stream')
          xhr.setRequestHeader('Authorization', 'UpToken ' + this.QNYtoken)
          xhr.send(pic)
        }
      },
      saveInfo () {
        let obj = {
          user_id: this.$store.state.user_id,
          token: this.$store.state.token
        }
        let length = this.saveData.length
        if (length === 0) {
          obj['no_upload'] = 1
        } else {
          obj['attachment_pic'] = this.saveData
        }
        this.axios.post('/api/guarantee/upload_attachment_pic', obj)
        .then((res) => {
          let data = res.data
          this.loadingIsShow = false
          if (data.code === 1) {
            this.$store.commit('profileStepSet', 4)
            this.$router.push('/warrantor/manage')
          } else {
            $().Mnews(data.desc, 1000)
          }
        })
      },
      deleteImg (index) {
        this.base64Image.splice(index, 1)
        this.photoImg.splice(index, 1)
        this.isMax = false
      },
      addUpLoadEvent (el, lockWidth, callback) {
        fileRead(el, {
          readAs: 'dataurl',
          zip: true,
          zipWidth: lockWidth,
          zipQuality: 0.7,
          loadStart: () => {
            this.loadingIsShow = true
          },
          loadEnd: () => {
            setTimeout(() => {
              this.loadingIsShow = false
            }, 300)
          },
          success: (result, resultHandle) => {
            callback(result, resultHandle)
          },
          error: function (msg) {
            $().Mnews(msg, 1000)
          }
        })
      },
      hideMask () {
        this.maskIsShow = false
      },
      showMask () {
        this.maskIsShow = true
      }
    },
    created () {
      this.setTitle(this.title)
    },
    mounted () {
      let inputFile = $('.fileInput')
      let inputFileLen = inputFile.length
      let addFile = this.$refs.addInput
      let lockWidth = inputFile.offsetWidth * 2
      for (let i = 0; i < inputFileLen; i++) {
        this.addUpLoadEvent(inputFile[i], lockWidth, (result, resultHandle) => {
          this.base64Image[i] = resultHandle[0]
          this.photoImg[i] = result[0]
        })
      }
      this.addUpLoadEvent(addFile, lockWidth, (result, resultHandle) => {
        if (this.base64Image.length < 3) {
          this.base64Image.push(resultHandle[0])
          this.photoImg.push(result[0])
          if (this.base64Image.length === 3) {
            this.isMax = true
          }
        }
      })
    }
  }
</script>
<style lang="scss" scoped>
  @import '../../assets/css/function.scss';
  @import '../../styles/form.scss';
  .form{
    padding-bottom: rem(100);
    .file-block{
      .photo{
        padding: 0;
        h5{
          padding: rem(25) rem(24);
          font-size: rem(26);
          color: #333;
          span{
            color: #72a5ef;
          }
        }
        .add{
          position: relative;
          padding: rem(25) 0;
          display: block;
          width: rem(150);
          margin: 0 auto;
          font-size: rem(26);
          color: #72a5ef;
          text-align: center;
          input[type=file]{
            position: absolute;
            top: 0;
            left: 50%;
            margin-left: rem(-75);
            width: rem(150);
            height: 100%;
            opacity: 0;
          }
        }
        .container{
          margin-bottom: rem(10);
          position: relative;
          .iconfont{
            position: absolute;
            top: 40%;
            right: rem(100);
            font-size: rem(46);
            color: #666;
          }
        }
      }
    }
  }
  .form-footer{
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
  }
  .mask{
    .content{
      position: absolute;
      top: 25%;
      left: 0;
      width: 100%;
      padding: 0 rem(75);
      .tips{
        margin-bottom: rem(40);
        background: #fff;
        padding: rem(60) rem(40) rem(90);
        border-radius: 6px;
        font-size: rem(28);
        color: #333;
        img{
          display: block;
          margin: 0 0 rem(35) 37%;
          width: rem(215);
          height: rem(173);
        }
        p{
          margin-bottom: rem(35);
          line-height: 180%;
        }
        input[type=button]{
          display: block;
          width: 100%;
          height: rem(72);
          background: #72a5ef;
          font-size: rem(34);
          color: #fff;
          border-radius: 4px;
        }
        h2{
          margin-bottom: rem(35);
          font-size: rem(36);
          color: #141414;
          text-align: center;
          font-weight: bold;
        }
        .gray{
          color: #666;
          line-height: 200%;
        }
      }
      .close{
        text-align: center;
        .iconfont{
          font-size: rem(58);
          color: #fff;
        }
      }
    }
  }
  .next:disabled{
    background: #d0d0d0;
  }
</style>
